<?php
/**
 * @package Autogenerator for Joomla!
 * @version 3.0.0
 * @author Truong Cong Duc <truongcongduc4@gmail.com>
 * @link autogenerator.blogspot.com
 * @copyright (c) 2013, Truong Cong Duc
 * @license GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

JLoader::register('AutogeneratorHelper', AUTOGENERATOR_DIR_ROOT . '/helpers/autogenerator.php');

class AutogeneratorModelTable extends JModelAdmin {

    protected $text_prefix = 'COM_AUTOGENERATOR';

    public function getForm($data = array(), $loadData = true) {
        $form = $this->loadForm('com_autogenerator.table', 'table', array('control' => 'jform', 'load_data' => $loadData));

        if (empty($form)) {
            return false;
        }

        return $form;
    }

    public function getTable($type = 'Table', $prefix = 'AutogeneratorTable', $config = array()) {
        return JTable::getInstance($type, $prefix, $config);
    }

    protected function loadFormData() {
        $data = JFactory::getApplication()->getUserState('com_autogenerator.edit.table.data', array());

        if (empty($data)) {
            $data = $this->getItem();
        }

        return $data;
    }

    protected function getReorderConditions($oTable) {
        $oCondition = array();
        $oCondition[] = 'component_id = ' . (int) $oTable->component_id;
        return $oCondition;
    }

    protected function prepareTable($oTable) {
        if (empty($oTable->id)) {
            if (empty($oTable->ordering)) {
                $oDatabase = JFactory::getDbo();

                $oDatabase->setQuery('SELECT MAX(ordering) FROM #__auto_table');

                $iMax = $oDatabase->loadResult();

                $oTable->ordering = $iMax + 1;
            }
        }
    }

    public function getAllFieldsInDatabaseByTableId($iTableId = 0) {
        $oTable = $this->getItem($iTableId);

        $strTableName = trim($oTable->sql_table_name);

        $aFields = array();

        if ($strTableName != '') {
            $oDatabase = JFactory::getDbo();

            $oDatabase->setQuery('SHOW TABLES LIKE ' . $oDatabase->quote($oDatabase->escape($strTableName)));

            // Check table exist or not.
            $aResult = $oDatabase->loadObject();

            $aFields = array();

            if (count($aResult) > 0) {
                // Clear the query.
                $oDatabase->getQuery(true);

                $oDatabase->setQuery('SHOW COLUMNS FROM ' . $oDatabase->quoteName($oDatabase->escape($strTableName)));

                $aFields = $oDatabase->loadObjectList();
            }
        }

        return $aFields;
    }
    /**
     * @see JTable
     * @param type $aData
     * @return boolean
     */
    public function storeField($aData) {
        $oTable = JTable::getInstance('Field', 'AutogeneratorTable');

        $sKey = $oTable->getKeyName();

        $iPrimaryKey = (!empty($aData[$sKey])) ? $aData[$sKey] : 0;

        $bIsNew = true;

        // Allow an exception to be thrown.
        try {
            // Load the row if saving an existing record.
            if ($iPrimaryKey > 0) {
                $oTable->load($iPrimaryKey);

                $bIsNew = false;
            }

            // Bind the data.
            if (!$oTable->bind($aData)) {
                $this->setError($oTable->getError());

                return false;
            }

            // Check the data.
            if (!$oTable->check()) {
                $this->setError($oTable->getError());
                return false;
            }

            // Store the data.
            if (!$oTable->store()) {
                $this->setError($oTable->getError());
                return false;
            }
        } catch (Exception $oException) {
            $this->setError($oException->getMessage());

            return false;
        }

        return isset($oTable->$sKey) ? $oTable->$sKey : false;
    }

    public function editInline($aData) {
        $iKey = (int) $aData['id'];
        if ($iKey < 1) {
            return false;
        }

        $oTable = $this->getTable();

        // Allow an exception to be thrown.
        try {
            // Load the row if saving an existing record.
            if ($iKey > 0) {
                if (!$oTable->load($iKey)) {
                    return false;
                }
            }

            // Bind the data.
            if (!$oTable->bind($aData)) {
                $this->setError($oTable->getError());
                return false;
            }

            // Prepare the row for saving
            $this->prepareTable($oTable);

            // Check the data.
            if (!$oTable->check()) {
                $this->setError($oTable->getError());
                return false;
            }

            // Store the data.
            if (!$oTable->store()) {
                $this->setError($oTable->getError());
                return false;
            }

            // Clean the cache.
            $this->cleanCache();
        } catch (Exception $e) {
            $this->setError($e->getMessage());

            return false;
        }

        $pkName = $oTable->getKeyName();

        if (isset($oTable->$pkName)) {
            return $oTable->$pkName;
        }

        return true;
    }

    public function deleteAllFields($iTableId) {
        $oDatabase = JFactory::getDbo();

        $oQuery = $oDatabase->getQuery(true);
        $oQuery->delete($oDatabase->quoteName('#__auto_field'));
        $oQuery->where('table_id = ' . (int) $iTableId);

        $oDatabase->setQuery($oQuery);
        try {
            $bResult = $oDatabase->query();
        } catch (Exception $e) {
            if ($sError = $oDatabase->getErrorMsg()) {
                return $sError;
            }
        }
        return $bResult;
    }

    /**
     * For ajax.
     */
    public function changeStatus($iTableId) {
        $iKey = (int) $iTableId;
        if ($iKey < 1) {
            return JText::_('COM_AUTOGENERATOR_TABLE_AJAX_ERROR_MESSAGE_TABLE_NOT_VALID');
        }

        $oTable = $this->getTable();

        // Allow an exception to be thrown.
        try {
            // Load the row if saving an existing record.
            if ($iKey > 0) {
                if (!$oTable->load($iKey)) {
                    return JText::_('COM_AUTOGENERATOR_TABLE_AJAX_ERROR_MESSAGE_TABLE_NOT_VALID');
                }
            }

            if (intval($oTable->id) == 0) {
                return JText::_('COM_AUTOGENERATOR_TABLE_AJAX_ERROR_MESSAGE_TABLE_NOT_VALID');
            }

            // Change the status.
            if ($oTable->status == 1)
                $oTable->status = 0;
            else
                $oTable->status = 1;

            // Prepare the row for saving
            $this->prepareTable($oTable);

            // Check the data.
            if (!$oTable->check()) {
                return $oTable->getError();
            }

            // Store the data.
            if (!$oTable->store()) {
                return $oTable->getError();
            }

            // Clean the cache.
            $this->cleanCache();
        } catch (Exception $e) {
            return $e->getMessage();
        }

        return $oTable->status;
    }

    public function delete(&$pks) {
        $oModelFields = JModelLegacy::getInstance('Fields', 'AutogeneratorModel');
        $oModelMvcs = JModelLegacy::getInstance('Mvcs', 'AutogeneratorModel');
        
        foreach ($pks as $iTableId) {
            $oModelFields->deleteAllFieldsByTableId($iTableId);
            $oModelMvcs->deleleAllMVCsByTableId($iTableId);
        }
        
        return parent::delete($pks);
    }
    
}
